"""
Storage service for specification fixing operations.

Provides JSON file storage and data persistence utilities
for specifications, analysis results, and configuration data.
"""

import json
import os
from pathlib import Path
from typing import Dict, Any, Optional, List
from datetime import datetime

from ..utils.logger import get_logger
from ..utils.exceptions import StorageError

logger = get_logger(__name__)


class StorageService:
    """Service for handling file-based storage operations."""

    def __init__(self, base_path: Optional[str] = None):
        """Initialize storage service with base path."""
        self.base_path = Path(base_path) if base_path else Path.cwd()
        self.data_dir = self.base_path / "data"
        self.ensure_data_directory()

    def ensure_data_directory(self) -> None:
        """Ensure data directory exists."""
        self.data_dir.mkdir(exist_ok=True)
        logger.debug(f"Data directory ensured: {self.data_dir}")

    def save_json(self, data: Dict[str, Any], filename: str,
                  subdirectory: Optional[str] = None) -> str:
        """
        Save data as JSON file.

        Args:
            data: Data to save
            filename: Target filename
            subdirectory: Optional subdirectory within data directory

        Returns:
            Full path to saved file

        Raises:
            StorageError: If save operation fails
        """
        try:
            if subdirectory:
                target_dir = self.data_dir / subdirectory
                target_dir.mkdir(exist_ok=True)
                file_path = target_dir / filename
            else:
                file_path = self.data_dir / filename

            with open(file_path, 'w', encoding='utf-8') as f:
                json.dump(data, f, ensure_ascii=False, indent=2)

            logger.info(f"Data saved to: {file_path}")
            return str(file_path)

        except Exception as e:
            logger.error(f"Failed to save data to {filename}: {e}")
            raise StorageError(f"Failed to save data: {e}")

    def load_json(self, filename: str,
                  subdirectory: Optional[str] = None) -> Dict[str, Any]:
        """
        Load data from JSON file.

        Args:
            filename: Target filename
            subdirectory: Optional subdirectory within data directory

        Returns:
            Loaded data

        Raises:
            StorageError: If load operation fails
        """
        try:
            if subdirectory:
                file_path = self.data_dir / subdirectory / filename
            else:
                file_path = self.data_dir / filename

            if not file_path.exists():
                raise FileNotFoundError(f"File not found: {file_path}")

            with open(file_path, 'r', encoding='utf-8') as f:
                data = json.load(f)

            logger.debug(f"Data loaded from: {file_path}")
            return data

        except FileNotFoundError:
            logger.warning(f"File not found: {filename}")
            raise
        except Exception as e:
            logger.error(f"Failed to load data from {filename}: {e}")
            raise StorageError(f"Failed to load data: {e}")

    def file_exists(self, filename: str,
                   subdirectory: Optional[str] = None) -> bool:
        """Check if file exists."""
        if subdirectory:
            file_path = self.data_dir / subdirectory / filename
        else:
            file_path = self.data_dir / filename
        return file_path.exists()

    def delete_file(self, filename: str,
                    subdirectory: Optional[str] = None) -> bool:
        """Delete a file."""
        try:
            if subdirectory:
                file_path = self.data_dir / subdirectory / filename
            else:
                file_path = self.data_dir / filename

            if file_path.exists():
                file_path.unlink()
                logger.info(f"File deleted: {file_path}")
                return True
            return False

        except Exception as e:
            logger.error(f"Failed to delete file {filename}: {e}")
            raise StorageError(f"Failed to delete file: {e}")

    def list_files(self, subdirectory: Optional[str] = None,
                   pattern: str = "*") -> List[str]:
        """List files in directory."""
        try:
            if subdirectory:
                target_dir = self.data_dir / subdirectory
            else:
                target_dir = self.data_dir

            if not target_dir.exists():
                return []

            files = []
            for file_path in target_dir.glob(pattern):
                if file_path.is_file():
                    files.append(file_path.name)

            return sorted(files)

        except Exception as e:
            logger.error(f"Failed to list files: {e}")
            raise StorageError(f"Failed to list files: {e}")

    def get_file_timestamp(self, filename: str,
                          subdirectory: Optional[str] = None) -> Optional[datetime]:
        """Get file modification timestamp."""
        try:
            if subdirectory:
                file_path = self.data_dir / subdirectory / filename
            else:
                file_path = self.data_dir / filename

            if not file_path.exists():
                return None

            timestamp = file_path.stat().st_mtime
            return datetime.fromtimestamp(timestamp)

        except Exception as e:
            logger.error(f"Failed to get timestamp for {filename}: {e}")
            return None

    def backup_file(self, filename: str,
                   subdirectory: Optional[str] = None) -> Optional[str]:
        """Create backup of file with timestamp."""
        try:
            if subdirectory:
                file_path = self.data_dir / subdirectory / filename
                backup_dir = self.data_dir / subdirectory / "backups"
            else:
                file_path = self.data_dir / filename
                backup_dir = self.data_dir / "backups"

            if not file_path.exists():
                return None

            backup_dir.mkdir(exist_ok=True)
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            backup_filename = f"{filename}.{timestamp}.bak"
            backup_path = backup_dir / backup_filename

            # Copy file content
            data = self.load_json(filename, subdirectory)
            self.save_json(data, backup_filename,
                          subdirectory + "/backups" if subdirectory else "backups")

            logger.info(f"Backup created: {backup_path}")
            return str(backup_path)

        except Exception as e:
            logger.error(f"Failed to create backup for {filename}: {e}")
            return None